#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <arpa/inet.h>

//检查系统字序
const char* get_endianness() //endianness 字节顺序
{
    uint32_t test = 0x12345678;
    uint8_t* bytes = (uint8_t*)&test;
    return (bytes[0] == 0x12) ? "Big Endian" : "Little Endian";
}

void serialize_short(short value,uint8_t* buffer)
{
    uint16_t net_value = htons((uint16_t)value);
    memcpy(buffer,&net_value,sizeof(net_value));
}

short deserialize_short(const uint8_t* buffer)
{
    uint16_t net_value;
    memcpy(&net_value,buffer,sizeof(net_value));
    return (short)ntohs(net_value);
}

int main(int argc, char const *argv[])
{
    printf("系统字节序:%s\n",get_endianness());
    printf("short类型大小:%zu 字节\n\n",sizeof(short));

    
    short test_values[] = {0,1,-1,12345,-12345,32767,-32768};
    size_t num_values = sizeof(test_values)/sizeof(test_values[0]);

    for (size_t i = 0; i < num_values; i++)
    {
        short original = test_values[i];
        uint8_t buffer_network[2];
        uint8_t buffer_host[2];
        uint8_t buffer_le[2];

        printf("测试值： %d (0x%04x)\n",original,(unsigned short)original);

        serialize_short(original,buffer_network);
        short result_network = deserialize_short(buffer_network);

        printf("网络字节序 序列化:");
        for (size_t i = 0; i < sizeof(short); i++)
        {
            printf("%02x",buffer_network[i]);
            /* code */
        }

        printf("反序列化:%d\n",result_network);
        
    }
    

    return 0;
}
